#include "optionsifaces.h"

#include <QApplication>
#include<QDir>
#include <QtDeclarative>

OptionsIfaces::OptionsIfaces( QNMSettings * qset, QObject *_parent ) : QObject(_parent)
{
    parent = _parent;
    qset_this = qset;
    listModelIfaces = NULL;

    rootContext = NULL;
    pageNetworkInterfaces = NULL;
}

OptionsIfaces::~OptionsIfaces()
{
    /*if( listModelIfaces != NULL ) {
        delete listModelIfaces;
    }*/
}

void OptionsIfaces::myRootContext()
{
    QDeclarativeView *qmlObj = (QDeclarativeView*)(this->parent);
    QDeclarativeEngine *engine = qmlObj->engine();

    rootContext = engine->rootContext();

    pageNetworkInterfaces = (qmlObj->rootObject())->findChild<QObject*>( QString("pageDialogNetworkInterfaces") );
}


void OptionsIfaces::initListIfaces()
{
    /* список сетевых интерфейсов из настройки программы */
    QStringList listIfaces = qset_this->getListIfaces();

    //this->clearListIfacesModel();

    IfaceListModel *_listModelIfaces = new IfaceListModel(this);
    /*if( listModelIfaces == NULL ) {
        listModelIfaces = new IfaceListModel( this );
    }*/

    QStringList::const_iterator itr;
    for( itr = listIfaces.constBegin(); itr != listIfaces.constEnd(); itr++ )
    {
        QString ifaceName = *itr;
        QString strIfacePic = Utils::pixmapIface( ifaceName );
        IfaceItemModel *item = new IfaceItemModel( ifaceName, strIfacePic, this );
        //listModelIfaces->append( item );
        _listModelIfaces->append( item );
    }
    //emit listModelIfacesChanged();

    QDeclarativeView *qmlObj = (QDeclarativeView*)(this->parent);
    QDeclarativeEngine *engine = qmlObj->engine();
    engine->rootContext()->setContextProperty( "listIfacesMonitor", _listModelIfaces );
}

void OptionsIfaces::initIfconfig()
{
    QString txt_ip = qApp->translate( "OptionsIfaces", "IP address" );
    QString txt_mac = qApp->translate( "OptionsIfaces", "MAC address" );
    QString rx_b_p = qApp->translate( "OptionsIfaces", "RX bytes/RX packets" );
    QString tx_b_p = qApp->translate( "OptionsIfaces", "TX bytes/TX packets" );

    QString textIfcfg = "<html>";
    textIfcfg+= "<h2>Ifconfig:<h2>";
    textIfcfg+= "<dl style='font-size: 12pt;'>";

    QDir p("/sys/class/net");
    QStringList listdirVar = p.entryList( QDir::Dirs );
    QStringList::const_iterator itr;
    for( itr = listdirVar.constBegin(); itr != listdirVar.constEnd(); itr++ )
    {
        QString nif = *itr;
        if( (nif == ".") || (nif=="..") ) { continue; }
        QString p_stat = QString("/sys/class/net/")+nif+QString("/statistics/");
        QString p_dat = QString("/sys/class/net/")+nif+QString("/");
        QString rx_b = p_stat + QString("rx_bytes");
        QString rx_p = p_stat + QString("rx_packets");
        QString tx_b = p_stat + QString("tx_bytes");
        QString tx_p = p_stat + QString("tx_packets");
        QString mac_addr = p_dat + QString("address");

        QString mac = this->fileData( mac_addr );
        QString rxb = this->fileData( rx_b );
        QString rxp = this->fileData( rx_p );
        QString txb = this->fileData( tx_b );
        QString txp = this->fileData( tx_p );

        QStringList ipList = this->getIpIface( nif );
        textIfcfg += "<dt><b>"+nif+":</b></dt>";
        if( ipList.length() != 0 ) {
            for( int z=0; z<ipList.length(); z++ ) {
                textIfcfg += "<dd><b>"+txt_ip+":</b> " + ipList.at(z) + "</dd>";
            }
        }
        textIfcfg += "<dd><b>"+txt_mac+":</b> "+mac+"</dd>";
        textIfcfg += "<dd><b>"+rx_b_p+":</b> "+rxb+" / "+rxp+"</dd>";
        textIfcfg += "<dd><b>"+tx_b_p+":</b> "+txb+" / "+txp+"</dd>";
    }
    textIfcfg += "</dl>";
    textIfcfg += "</html>";

    QDeclarativeView *qmlObj = (QDeclarativeView*)(this->parent);
    pageNetworkInterfaces = (qmlObj->rootObject())->findChild<QObject*>( QString("pageDialogNetworkInterfaces") );
    if( pageNetworkInterfaces != NULL ) {
        QMetaObject::invokeMethod(pageNetworkInterfaces, "setTextIfconfig", Q_ARG(QVariant, textIfcfg));
    }
}


QStringList OptionsIfaces::getIpIface( const QString &iface ) const
{
    QStringList retList;
    QNetworkInterface qni = QNetworkInterface::interfaceFromName( iface );
    if( qni.isValid() )
    {
        //QString hwAddr = qni.hardwareAddress(); qDebug() << iface << " => " << hwAddr;
        QList<QNetworkAddressEntry> ipAddrList = qni.addressEntries();
        QList<QNetworkAddressEntry>::const_iterator itr;
        for( itr = ipAddrList.constBegin(); itr != ipAddrList.constEnd(); itr++ )
        {
            QNetworkAddressEntry pQListData = *(itr);
            QHostAddress qha = pQListData.ip();
            //qDebug() << iface << " => "<< qha.toString();
            retList.append( qha.toString() );
        }
    }
    return retList;
}


void OptionsIfaces::addIface( const QString &ifaceName )
{
    if( ifaceName == "" ) {
        return;
    }

    /* проверям, что такого интерфайса еще нет в списке */
    QStringList listIfaces = qset_this->getListIfaces();
    QStringList::const_iterator itr;
    for( itr = listIfaces.constBegin(); itr != listIfaces.constEnd(); itr++ )
    {
        QString currIfaceName = *itr;
        if( currIfaceName == ifaceName ) {
            if( pageNetworkInterfaces != NULL ) {
                QMetaObject::invokeMethod( pageNetworkInterfaces, "showDlgIfaceExists" );
                return;
            }
            return;
        }
    }

    /* добавим указанный пользователем сетевой интерфейс */
    listIfaces.append( ifaceName );
    qset_this->setListIfaces( listIfaces );
    this->initListIfaces();
}

void OptionsIfaces::removeIface( const int ifaceIndex )
{
    QStringList listIfaces = qset_this->getListIfaces();

    if( !((ifaceIndex >= 0) && (ifaceIndex < listIfaces.size())) ) {
        //iface_name_clicked_item.at( ifaceIndex );
        return; //индекс за пределами списка
    }

    /* проверка, что сетевой интерфейс не последний в списке */
    if( listIfaces.size() == 1 ) {
        if( pageNetworkInterfaces != NULL ) {
            QMetaObject::invokeMethod( pageNetworkInterfaces, "showDlgCantDeleteAllIface" );
            return;
        }
        return;
    }

    listIfaces.takeAt( ifaceIndex );
    qset_this->setListIfaces( listIfaces );
    this->initListIfaces();
}


void OptionsIfaces::clearListIfacesModel()
{
    /*int L = listModelIfaces->count();
    qDebug() << "OptionsIfaces::clearListIfacesModel(): L="<<L;
    for( int l=0; l<L; l++ ) {
        IfaceItemModel *item = (IfaceItemModel*)listModelIfaces->takeRow(l);
        qDebug() << l<<": OptionsIfaces::clearListIfacesModel(): L="<< item;
        if( item ) delete item;
    }*/
    if( listModelIfaces != NULL ) {
        listModelIfaces->clearList();
        //delete listModelIfaces;
        //listModelIfaces = NULL;
    }
    //listModelIfaces->clearList(); //нет необходимости в этом действии, если используется takeRow()
}

